﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Tools.Http;
using System.IO.Compression;

namespace Tools
{
    public class HttpHelp
    {
        public static string HttpPost(HttpInput input, bool isGZip)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(input.Url);

            request.Method = "POST";
            request.ServicePoint.Expect100Continue = false;
            request.KeepAlive = true;
            if (input.ContentType != null)
            {
                request.Headers.Add("ContentType", input.ContentType);
            }
            if (input.Cookie != null)
            {
                request.Headers.Add("Cookie", input.Cookie);
            }
            if (input.UserAgent != null)
            {
                request.Headers.Add("User-Agen", input.UserAgent);
            }
            if (input.AcceptEncoding != null)
            {
                request.Headers.Add("Accept-Encoding", input.AcceptEncoding);
            }
            if (input.AcceptLanguage != null)
            {
                request.Headers.Add("Accept-Language", input.AcceptLanguage);
            }
            if (input.Host != null)
            {
                request.Host = input.Host;
            }
            if (input.PostData != null)
            {
                byte[] data = Encoding.UTF8.GetBytes(input.PostData);

                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                }
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream resStream;
            if (isGZip)
            {
                resStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress);
            }
            else
            {
                resStream = response.GetResponseStream();
            }
            StreamReader resReader = new StreamReader(resStream, Encoding.UTF8);
            return resReader.ReadToEnd();


        }
    }
}
